package com.myna.csv.csv_file;

import com.myna.csv.batch.ProcessBatchQueues;
import com.myna.csv.domain.PropertyStr;
import com.myna.csv.utils.DataTypeUtils;
import com.myna.csv.utils.DateUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static com.myna.csv.initial.InitialProcessor.fileNumber;
import static com.myna.csv.initial.InitialProcessor.rdcFilePIPath;
import static com.myna.csv.initial.InitialProcessor.rdcFilePath;

public class WriteUnderlyingPIProcesser implements Runnable {

    public static final Logger logger = LogManager.getLogger(WriteStubISINProcesser.class);

    private static Long alreadyWriteCount = 1L;
    private static int file_seq = 1;
    private static boolean flagRun = true;
    private static String dateStr;

    FileOutputStream fOutputStream = null;
    ZipOutputStream zoutput = null;
    ZipEntry zEntry = null;

    public WriteUnderlyingPIProcesser() {

        try {
            dateStr = DateUtils.formatDate(new Date(), PropertyStr.dateCS_timestampFormat);

            String zip_fileName = rdcFilePIPath + PropertyStr.UNDERLYINGPI_FOLDER + PropertyStr.underlyingPIFileName + "-" + dateStr +
                    "-" + DataTypeUtils.getDecimalFormat(file_seq) + ".zip";
            String fileName = PropertyStr.underlyingPIFileName + "-" + dateStr + "-" + DataTypeUtils.getDecimalFormat(file_seq) + ".csv";

            File file = new File(zip_fileName);

            if (!file.exists()) {
                file.createNewFile();
                fOutputStream = new FileOutputStream(file);
                zoutput = new ZipOutputStream(fOutputStream);
                zEntry = new ZipEntry(fileName);
                zoutput.putNextEntry(zEntry);

                setFileTitle();

                file_seq++;
            } else if (file.exists()) {
                file.delete();
                file.createNewFile();
                fOutputStream = new FileOutputStream(file);
                zoutput = new ZipOutputStream(fOutputStream);
                zEntry = new ZipEntry(fileName);
                zoutput.putNextEntry(zEntry);
                setFileTitle();

                file_seq++;
            }
        } catch (IOException | ParseException ex) {
            logger.error("create zip file  has error", ex);
        }
    }

    public void setFileTitle() {

        String title = "\"PI\", \"type\", \"subtype\", \"rcsSubType\", \"propertyId\"," +
                "\"propertyName\", \"currValue\", \"validFrom\",\"validFromWithTime\"," +
                " \"validTo\", \"validToWithTime\"";
        String line = title + "\r\n";
        byte[] inputBuff = line.getBytes();
        try {
            zoutput.write(inputBuff);
        } catch (Exception ex) {
            logger.error("set File Title has error", ex);
        }
    }

    public ZipOutputStream createWriter() throws ParseException {

        String zip_fileName = rdcFilePIPath + PropertyStr.UNDERLYINGPI_FOLDER + PropertyStr.underlyingPIFileName + "-" + dateStr +
                "-" + DataTypeUtils.getDecimalFormat(file_seq) + ".zip";
        String fileName = PropertyStr.underlyingPIFileName + "-" + dateStr + "-" + DataTypeUtils.getDecimalFormat(file_seq) + ".csv";

        File file = new File(zip_fileName);
        if (!file.exists()) {
            try {
                file.createNewFile();

                fOutputStream = new FileOutputStream(file);
                zoutput = new ZipOutputStream(fOutputStream);
                zEntry = new ZipEntry(fileName);
                zoutput.putNextEntry(zEntry);
                setFileTitle();
                file_seq++;
            } catch (IOException ex) {
                logger.error("create zip file  has error", ex);
            }
        }
        return zoutput;
    }

    public void run() {
        while (flagRun) {
            if (PropertyStr.queue_Flag && !ProcessBatchQueues.underlyingPIQue.isEmpty()) {
                try {
//                    if (alreadyWriteCount % fileNumber == 0) {
//                        zoutput.closeEntry();
//                        zoutput.close();
//                        fOutputStream.close();
//                        zoutput = createWriter();
//                        alreadyWriteCount++;
//                    }

                    String underlying = ProcessBatchQueues.underlyingPIQue.poll();

                    byte[] inputBuff = new byte[4096];

                    if (underlying != null) {
                        String line = underlying + "\r\n";
                        inputBuff = line.getBytes();
                        try {
                            zoutput.write(inputBuff);
                        } catch (Exception ex) {
                            logger.error("write one line has error", ex);
                        }
                        alreadyWriteCount++;
                    }
                } catch (Exception ex) {
                    logger.error("write processer has error", ex);
                }
            } else if (!PropertyStr.queue_Flag && ProcessBatchQueues.underlyingPIQue.isEmpty()) {
                try {
                    zoutput.closeEntry();
                    zoutput.close();
                    fOutputStream.close();
                    flagRun = false;
                } catch (IOException ex) {
                    logger.error("write processer has error", ex);
                }
            }
        }
        logger.info("Write underlyingPI csv end!!");
    }
}

